package com.system.dao.impl;

import com.system.config.Jdbc;
import com.system.dao.CommentData;
import com.system.domin.Comment;
import com.system.untils.FormatOutput;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;

public class CommentDataMapper implements CommentData {
    private final Jdbc jb;
    private final FormatOutput fo;

    public CommentDataMapper() {
        this.jb = new Jdbc();
        this.fo = new FormatOutput();
    }


    // 加载数据到集合
    @Override
    public HashMap<Integer, Integer> loadAllTopics() {
        try {
            HashMap<Integer, Integer> map = new HashMap<>();
            String sql = "select * from publish_tb where isShow = 0";
            PreparedStatement pstmt = this.jb.prepareStatement(sql);
            ResultSet rs = pstmt.executeQuery();
            int index = 0;
            while (rs.next()) {
                map.put(++index,rs.getInt("id"));
            }
            return map;
        }catch (SQLException e)
        {
            throw new RuntimeException(e);
        }
    }

    // 用户输入的编号与数据库中的编号一一对应
    @Override
    public void showOption(int id) {
        try {
            HashMap<Integer, Integer> map = loadAllTopics();
            String sql = "select * from publish_tb where id = ?";
            PreparedStatement pstmt = this.jb.prepareStatement(sql);
            pstmt.setInt(1, map.get(id));
            ResultSet rs = pstmt.executeQuery();
            if (rs.next())
            {
                System.out.println("  "+rs.getString("name")+":");
                System.out.println("\t\t"+rs.getString("text"));
                System.out.println("------------------------------------------------------------");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    // 深度 0 comment
    @Override
    public void addCommentText(String email, String text, int publishId) {
        // 使用 try-with-resources 来确保资源被正确关闭
        String sql = "insert into comments(email,publish_id,userName,content,timestamp,parent_id,status,unread,aimEmail) values(?,?,?,?,?,?,?,?,?)";
        try (PreparedStatement pstmt = this.jb.prepareStatement(sql)) {
            HashMap<Integer, Integer> map = loadAllTopics();
            String publishTime = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date());
            Comment comment = new Comment(getEmail(map.get(publishId)), map.get(publishId), getName(email), text, publishTime, 0);
            pstmt.setString(1, comment.getEmail());
            pstmt.setInt(2, comment.getPublishID());
            pstmt.setString(3, comment.getUserName());
            pstmt.setString(4, comment.getContext());
            pstmt.setString(5, comment.getTimestamp());
            pstmt.setInt(6, comment.getParent_id());
            pstmt.setString(7, comment.getStatus());
            pstmt.setInt(8, comment.getUnread());
            pstmt.setString(9, email);

            pstmt.executeUpdate();
        } catch (SQLException e) {
            // 打印异常信息，并在必要时进行更详细的处理
            throw new RuntimeException("Error inserting comment into database", e);
        }
    }

    public String getEmail(int publishId) {
        try {
            String sql = "select * from publish_tb where id='"+publishId+"'";
            ResultSet rs = jb.getStmt().executeQuery(sql);
            if (rs.next())
            {
                return rs.getString("email");
            }

        }catch (SQLException e)
        {
            throw new RuntimeException(e);
        }
        return null;
    }

    public String getName(String email) {
        try {
            String sql = "select * from memouser where email='"+email+"'";
            ResultSet rs = jb.getStmt().executeQuery(sql);
            if (rs.next())
            {
                return rs.getString("name");
            }

        }catch (SQLException e)
        {
            throw new RuntimeException(e);
        }
        return null;
    }

    @Override
    public void selectAllCommentDeep(int currentPage,int id) {
        try {
            int pageSize = 5;
            int offset = (currentPage - 1) * pageSize;  // 计算查询的偏移量
            // id->当前评论  parent_id -->
            String sql = "SELECT * FROM comments WHERE  publish_id = ? and parent_id = ? LIMIT ? OFFSET ?";
            PreparedStatement pstmt = jb.prepareStatement(sql);
            pstmt.setInt(1, id);
            pstmt.setInt(2, 0);
            pstmt.setInt(3, pageSize);  // 每页显示 5 条
            pstmt.setInt(4, offset);    // 偏移量

            ResultSet rs = pstmt.executeQuery();
            int index = offset;
            while (rs.next()) {
                String name = rs.getString("userName");
                String text = rs.getString("content");
                String time = rs.getString("timestamp");
                // 根据 text 长度显示内容
                if (text.length() > 20) {
                    System.out.println("------------------------------------------------------------");
                    System.out.println(" "+(++index) +"  "+name+":");
                    System.out.println(" "+ fo.formatStringByLength(text, 20)+"\t-->"+time);
                    System.out.println("------------------------------------------------------------");
                } else {
                    System.out.println("------------------------------------------------------------");
                    System.out.println(" "+(++index) +"  "+name+":");
                    System.out.println(" "+text+"\t-->"+time);
                    System.out.println("------------------------------------------------------------");
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int getTotalComments(int publish_id) {
        int totalRecords = 0;
        try {
            String sql = "SELECT COUNT(*) FROM comments where publish_id = ? and parent_id = ?";
            PreparedStatement pstmt = jb.prepareStatement(sql);
            pstmt.setInt(1,publish_id);
            pstmt.setInt(2,0);
            ResultSet rs = pstmt.executeQuery();
            // 处理结果集
            if (rs.next()) {
                totalRecords = rs.getInt(1); // 获取查询结果中的第一列，即记录数
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return totalRecords;
    }

    @Override
    public HashMap<Integer, Integer> getCommentID(int publishId) {
        try {
            HashMap<Integer, Integer> map = new HashMap<>();
            String sql = "SELECT * FROM comments WHERE  publish_id = ? and parent_id = 0";
            PreparedStatement pstmt = jb.prepareStatement(sql);
            pstmt.setInt(1,publishId);
            ResultSet rs = pstmt.executeQuery();
            int index = 1;
            while (rs.next())
            {
                int id = rs.getInt("id");
                map.put(index++,id);
            }
            return map;
        }catch (SQLException e)
        {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void show(int id) {
        try {
            String sql = "select * from publish_tb where id = ?";
            PreparedStatement pstmt = this.jb.prepareStatement(sql);
            pstmt.setInt(1, id);
            ResultSet rs = pstmt.executeQuery();
            if (rs.next())
            {
                System.out.println("  "+rs.getString("name")+":");
                System.out.println("\t\t"+rs.getString("text"));
                System.out.println("------------------------------------------------------------");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void showNotion(int id) {
        try {
            String sql = "select * from publish_tb where id = ?";
            PreparedStatement pstmt = this.jb.prepareStatement(sql);
            pstmt.setInt(1, id);
            ResultSet rs = pstmt.executeQuery();
            if (rs.next())
            {
                System.out.println("  "+rs.getString("name")+":");
                System.out.println("\t\t"+rs.getString("text"));
                System.out.println("------------------------------------------------------------");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
